const Router = require('koa-router');
const router = new Router();
const pool = require('../db');

// 获取所有歌手
router.get('/api/songers', async (ctx) => {
    try {
        const [songers] = await pool.execute('SELECT id, name, created_at FROM songers ORDER BY id DESC');
        ctx.body = {
            success: true,
            data: songers
        };
    } catch (error) {
        console.error('获取歌手列表失败:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '获取歌手列表失败'
        };
    }
});

// 添加新歌手
router.post('/api/songers', async (ctx) => {
    try {
        const { name } = ctx.request.body;
        
        if (!name) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '歌手名不能为空'
            };
            return;
        }
        
        // 检查歌手是否已存在
        const [existingSongers] = await pool.execute('SELECT id FROM songers WHERE name = ?', [name]);
        
        if (existingSongers.length > 0) {
            const [[row]] = await pool.execute('SELECT id, name, created_at FROM songers WHERE name = ?', [name]);
            ctx.body = {
                success: true,
                data: row,
                message: '歌手已存在'
            };
            return;
        }
        
        // 插入新歌手
        const [result] = await pool.execute(
            'INSERT INTO songers (name) VALUES (?)',
            [name]
        );

        const [[row]] = await pool.execute('SELECT id, name, created_at FROM songers WHERE id = ?', [result.insertId]);
        
        ctx.body = {
            success: true,
            data: row,
            message: '歌手添加成功'
        };
        
        console.log('歌手添加成功:', row);
        
    } catch (error) {
        console.error('添加歌手失败:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '添加歌手失败'
        };
    }
});

// 删除歌手
router.delete('/api/songers/:id', async (ctx) => {
    try {
        const { id } = ctx.params;
        
        const [result] = await pool.execute('DELETE FROM songers WHERE id = ?', [id]);
        
        if (result.affectedRows === 0) {
            ctx.status = 404;
            ctx.body = {
                success: false,
                message: '歌手不存在'
            };
            return;
        }
        
        ctx.body = {
            success: true,
            message: '歌手删除成功'
        };
        
    } catch (error) {
        console.error('删除歌手失败:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '删除歌手失败'
        };
    }
});

module.exports = router;

